<?php
namespace app\index\controller\traits;

use app\index\model\Cron;
trait Logger
{

    /**
     * 日志分类位置初始化
     *
     * @return   [type]
     */
    public function logInit($folder)
    {
        Log::init([
            'type' => 'File',
            'path' => APP_PATH . 'index' . DS . 'logs' . DS . $folder . DS,
        ]);
    }

    /**
     * 记录操作起始时间
     *
     * @return   void
     */
    public function addStartLog($operation)
    {

        Log::record('start' . $operation . ' at ' . date("Y-m-d H:i:s"));

        Debug::remark('begin');

        //日志组装
        switch ($operation) {
            case 'compute':
                $type = 0;
                break;
            case 'scan':
                $type = 1;
                break;
            case 'issue':
                $type = 2;
                break;
        }
        $data['type']        = $type;
        $data['start_at']    = date("Y-m-d H:i:s");
        $data['create_time'] = $data['start_at'];

        $model = new Cron();

        //新增日志
        $model->isUpdate(false)->save($data);
        return $model->id;
    }

    /**
     * 记录操作结束时间
     *
     * @return   void
     */
    public function addEndLog($operation, $id)
    {

        Log::record('end' . $operation . ' at ' . date("Y-m-d H:i:s"));

        $rec = Cron::get($id);

        $rec->end_at      = date("Y-m-d H:i:s");
        $rec->update_time = $rec->end_at;

        //计算持续时间并保存
        Debug::remark('end');

        $rec->last_time = Debug::getRangeTime('begin', 'end');
        $rec->mem_peak  = Debug::getMemPeak('begin', 'end');
        $rec->mem_range = Debug::getRangeMem('begin', 'end');
        $rec->mem_use   = Debug::getUseMem();

        $rec->isUpdate(true)->save();
    }
}
